app.push(function(){
    var Order = function(){
        var order = false;
        var orderData = false;
        var getDataMode = 'get';
        var currentShop = 0;
        this.init = function(url){
            url = app.cloneArray(url || app.currentUrl);
            if(url[1] == 'add'){
                url[1] = 'edit';
                currentShop = url[2] + '';
                url[2] = false;
            }
            if(this[url[1]])this[url[1]](url);
            else this.showData(url[1]);
        }
        this.showData = function(id){
            mlhAPI.order.get(
            {
                id: id,
                callback: function(data){
                    app.leftMenu.hide();
                    app.main.unmask();
                    if(data['result'] == 'success'){
                        app.topMenu.breadcrumbList[1] = ['Список заказов','#order/list/' + data.data.element.shop];
                        app.topMenu.breadcrumbList[2] = [data.data.element.title,'#order/' + data.data.element.order_id];
                        app.topMenu.buildBreadcrumb();
                        var paramsData = [];
                        $(data.data.element.param_data).each(function(){
                            paramsData[this.param_id] = this.small_value || this.long_value;
                        });
                        var extendFunctions = {
                            getTPL: function(type){
                                return 'param_show_field_type_' + type;
                            },
                            list: function(list){
                                var ret = [];
                                $(list.split(',')).each(function(){
                                    ret.push($.trim(this));
                                });
                                return ret;
                            }
                        };
                        $(data.data.element.params).each(function(){
                            this['currentValue'] = paramsData[this.param_id];
                            this['getTPL'] = extendFunctions.getTPL;
                            this['list'] = extendFunctions.list;
                        });
                        data.data.element['tags_count'] = data.data.element.tags.length;
                        console.log(data.data.element);
        				$.tmpl( 'order_content', data.data.element).prependTo(app.elements.general_content.html(''));
                        app.decorate.imageGallery(app.elements.general_content.find('[rel=orderImages]'),data.data.element.image,data.data.element.image_id);
        				if(data.data.element.model == 'page') return;
        				app.elements['comments'] = app.elements.general_content.find('#comments');
        				mlhAPI.order.getComments(
                        {
                            id: data.data.element.order_id,
                            callback: app.comments.showComments
                        });
                        app.decorate.setEvents(app.elements.general_content);
                    }
                }
            })
        }
        this.edit = function(url){
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            order = url[2] ? url[2] : false;
            if(order){
                mlhAPI.get({
                    c: 'order',
                    v: 'display',
                    id: order,
                    requestType: 'get_nc'
                },function(data){
                    console.log("Order data", data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    currentShop = data.data.element['shop'];
                    orderData = workWithData(data.data.element,data);
                    this_.build(orderData);
                    app.topMenu.breadcrumbList[1] = ['Список заказов','#order/list/' + currentShop];
                    app.topMenu.breadcrumbList[2] = ["№"+order,'#order/edit/' + order];
                    app.topMenu.buildBreadcrumb();
                    app.leftMenu.setEditShopLeftMenu(currentShop);
                });
                $('#orderEditForm button[type=submit]').text('Редактировать заказ');
            }
            
        }
        var workWithData = function(list,data){
            var totallPrice = 0;
            var totallCount = 0;
            var c = 0;
            $(list['orderList']).each(function(){
                var product = this;
                totallPrice+=product['totallPrice']*1;
                totallCount+=product['product_count']*1;
                product['zIndex'] = list['orderList'].length - (c++);
                product['params'] = product['params'] && product['params']!="{}" ? eval("("+product['params']+")") : false;
                if(product.params.params){
                    $(product.params.params).each(function(){
                        if(this['price']*1){
                            totallPrice += this['price']*1;
                            product['totallPrice'] = product['totallPrice']*1 + this['price']*1;
                        }
                    })
                }
            });
            if(list['coupon_id'] && list['coupon_percent']){
                totallPrice-=(totallPrice/100)*list['coupon_percent'];
            }
            list['totallPrice'] = totallPrice;
            list['totallCount'] = totallCount;
            list['currency'] = data.data.currency;
            list['status_list'] = [{id:0,name:'На стадии заполнения'},{id:1,name:'Заполнен и сохранён'},{id:2,name:'Просмотрен'},{id:3,name:'Выполняется'},{id:4,name:'Выполнен'},{id:5,name:'Отказан'}];
            list['status_title'] = list['status_list'][list['status']].name;

            return list;
                        
        }
        this.build = function(data){
            jQuery.extend(data, {
                editMode: order!=false
            });
            var el = $.tmpl('edit_order',data);
            el.prependTo(app.elements.general_content.html(''));
            el.find('select[name=status]').val(data.status);
            $('#orderEditForm form').submit(function(){
                var formData = {
                    callback: function(data){
                        console.log(data);
                        if(data.data['errors'] || data.data['error'] || data.result == "error"){
                            var text = "";
                            if(data.data['errors']){
                                for(var k in data.data.errors){
                                    if(k=='email')$('#orderEditForm input[name=email]').parents('.control-group:first').attr('class','row control-group error');
                                    text += "<div>" + data.data.errors[k] +"</div>";
                                }
                            }else{
                                text += "<div>" + data.data['error'] +"</div>";
                            }
                            $('#orderEditForm button[type=submit]').attr('class', 'btn btn-warning');
                        }else{
                            //$('#orderEditForm').find('.alert-info').html(order ? 'Вы успешно отредактировали продукт' : 'Вы успешно создали продукт').show();
                            $('#orderEditForm button[type=submit]').attr('class', 'btn btn-success');
                            app.static.success({description:(order ? 'Вы успешно отредактировали заказ' : 'Вы успешно создали заказ')})
                            getDataMode = 'get_rc';
                            app.go('#order/list/' + currentShop);
                        }
                    }
                }
                formData['order_id'] = order;
                var sData = $(this).serializeArray();
                for(var i = 0; i < sData.length; i++) {
                    formData[sData[i].name] = sData[i].value;
                }
                formData['model'] = 'order';
                formData['shop'] = currentShop;
                console.log(formData);
                mlhAPI.order.set(formData);
                return false;
            });
        }
        this.list = function(){
            var orderContainer = false;
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            if(!app.currentUrl[2]){
                app.go('#shop/list');
                return;
            }
            currentShop = app.currentUrl[2];
            app.topMenu.breadcrumbList[1] = ['Список заказов','#order/list/'+currentShop];
            app.topMenu.breadcrumbList[2] = false;
            app.topMenu.buildBreadcrumb();
            app.leftMenu.setEditShopLeftMenu(currentShop);
            var el = $.tmpl('manage_order_list', 
            {
                show_select: app.user_info.user_order > 1,
                shop: currentShop
            });
            orderContainer = $(el).find('[rel=order_list]:first');
            el.prependTo(app.elements.general_content.html(''));
            mlhAPI.order.getList({
                shop: currentShop,
                requestType: getDataMode,
                callback: function(data){
                    console.log(data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    orderContainer.html(data.data.list.length ? '' : 'Нет заказов');
                    for(var i in data.data.list){
                        list = workWithData(data.data.list[i],data);
                        var el = $.tmpl('manage_order_element', list);
                        el.prependTo(orderContainer);
                        app.decorate.setEvents(el);
                    }
                }
            });
            getDataMode = 'get';
        }
        var setParams = function(category_id){
            var paramContainer = $('#order_params_list').html(' ');
            if(category_id>0){
                mlhAPI.param.getList({
                    category_id: category_id,
                    callback: function(data){
                        console.log(data);
                        if(data.result=='error'){
                            return;
                        }
                        var el = $.tmpl('param_edit_field', data.data.list, {
                            getTPL: function(type){
                                return 'param_edit_field_type_' + type;
                            },
                            list: function(list){
                                var ret = [];
                                $(list.split(',')).each(function(){
                                    ret.push($.trim(this));
                                });
                                return ret;
                            }
                        });
                        app.decorate.setEvents(el);
                        el.appendTo(paramContainer);
                        if(orderData && orderData['category_id'] == category_id){
                            $(orderData.param_data).each(function(){
                                var el = $("#order_params_list [name='param_[" + this.param_id + "]']");
                                if(el[0].tagName == "INPUT" && el[0].type=="checkbox" && (this.small_value || this.long_value)) {
                                    el.attr('checked','checked');
                                    return;
                                }
                                el.val(this.small_value || this.long_value);
                            });
                        }
                        $('#order_params').show();
                    }
                });
            }
            if(category_id>0)$('#order_params').show();
            else $('#order_params').hide();
        }
    }
    app['order'] = new Order();
});